package com.sf.ams.utils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;


public class StringUtil {

	public static final String AMOUNT_DOT =".";   
	
	//Excel sheetname 特殊处理 
	public static final String EXCEL_SHEET_NAME_REGEX ="[:*\\[\\]/?]"; 
	
	private StringUtil() {

	}

	public static boolean isEmpty(String str) {
		return str == null || str.length() == 0;
	}

	public static boolean isNotEmpty(String str) {
		return str != null && str.length() > 0;
	}

	public static boolean isBlank(String str) {
		if (str == null || str.length() == 0)
			return true;
		int strLen = str.length();
		for (int i = 0; i < strLen; i++)
			if (!Character.isWhitespace(str.charAt(i)))
				return false;

		return true;
	}
	
	public static boolean isEmptyOrBlank(String str){
		return isEmpty(str) || isBlank(str);
	}
	
	public static boolean isNotEmptyAndNotBlank(String str){
		return !isEmpty(str) && !isBlank(str);
	}

	public static boolean isNotBlank(String str) {
		if (str == null || str.length() == 0)
			return false;
		int strLen = str.length();
		for (int i = 0; i < strLen; i++)
			if (!Character.isWhitespace(str.charAt(i)))
				return true;

		return false;
	}

	public static boolean equals(String str1, String str2) {
		return str1 != null ? str1.equals(str2) : str2 == null;
	}

	public static boolean equalsIgnoreCase(String str1, String str2) {
		return str1 != null ? str1.equalsIgnoreCase(str2) : str2 == null;
	}

	public static int indexOf(String str, char searchChar) {
		if (str == null || str.length() == 0)
			return -1;
		else
			return str.indexOf(searchChar);
	}

	public static int indexOf(String str, char searchChar, int startPos) {
		if (str == null || str.length() == 0)
			return -1;
		else
			return str.indexOf(searchChar, startPos);
	}

	public static int indexOf(String str, String searchStr) {
		if (str == null || searchStr == null)
			return -1;
		else
			return str.indexOf(searchStr);
	}

	public static int indexOf(String str, String searchStr, int startPos) {
		if (str == null || searchStr == null)
			return -1;
		if (searchStr.length() == 0 && startPos >= str.length())
			return str.length();
		else
			return str.indexOf(searchStr, startPos);
	}

	public static int lastIndexOf(String str, char searchChar) {
		if (str == null || str.length() == 0)
			return -1;
		else
			return str.lastIndexOf(searchChar);
	}

	public static int lastIndexOf(String str, char searchChar, int startPos) {
		if (str == null || str.length() == 0)
			return -1;
		else
			return str.lastIndexOf(searchChar, startPos);
	}

	public static int lastIndexOf(String str, String searchStr) {
		if (str == null || searchStr == null)
			return -1;
		else
			return str.lastIndexOf(searchStr);
	}

	public static int lastIndexOf(String str, String searchStr, int startPos) {
		if (str == null || searchStr == null)
			return -1;
		else
			return str.lastIndexOf(searchStr, startPos);
	}

	public static boolean contains(String str, char searchChar) {
		if (str == null || str.length() == 0)
			return false;
		return str.indexOf(searchChar) >= 0;
	}

	public static boolean contains(String str, String searchStr) {
		if (str == null || searchStr == null)
			return false;
		return str.indexOf(searchStr) >= 0;
	}

	public static int indexOfAny(String str, char searchChars[]) {
		if (str == null || str.length() == 0 || searchChars == null
				|| searchChars.length == 0)
			return -1;
		for (int i = 0; i < str.length(); i++) {
			char ch = str.charAt(i);
			for (int j = 0; j < searchChars.length; j++)
				if (searchChars[j] == ch)
					return i;

		}

		return -1;
	}

	public static int indexOfAny(String str, String searchChars) {
		if (str == null || str.length() == 0 || searchChars == null
				|| searchChars.length() == 0)
			return -1;
		else
			return indexOfAny(str, searchChars.toCharArray());
	}

	public static int indexOfAnyBut(String str, char searchChars[]) {
		if (str == null || str.length() == 0 || searchChars == null
				|| searchChars.length == 0)
			return -1;
		label0: for (int i = 0; i < str.length(); i++) {
			char ch = str.charAt(i);
			for (int j = 0; j < searchChars.length; j++)
				if (searchChars[j] == ch)
					continue label0;

			return i;
		}

		return -1;
	}

	public static int indexOfAnyBut(String str, String searchChars) {
		if (str == null || str.length() == 0 || searchChars == null
				|| searchChars.length() == 0)
			return -1;
		for (int i = 0; i < str.length(); i++)
			if (searchChars.indexOf(str.charAt(i)) < 0)
				return i;

		return -1;
	}

	public static boolean containsOnly(String str, char valid[]) {
		if (valid == null || str == null)
			return false;
		if (str.length() == 0)
			return true;
		if (valid.length == 0)
			return false;
		return indexOfAnyBut(str, valid) == -1;
	}

	public static boolean containsOnly(String str, String validChars) {
		if (str == null || validChars == null)
			return false;
		else
			return containsOnly(str, validChars.toCharArray());
	}

	public static boolean containsNone(String str, char invalidChars[]) {
		if (str == null || invalidChars == null)
			return true;
		int strSize = str.length();
		int validSize = invalidChars.length;
		for (int i = 0; i < strSize; i++) {
			char ch = str.charAt(i);
			for (int j = 0; j < validSize; j++)
				if (invalidChars[j] == ch)
					return false;

		}

		return true;
	}

	public static boolean containsNone(String str, String invalidChars) {
		if (str == null || invalidChars == null)
			return true;
		else
			return containsNone(str, invalidChars.toCharArray());
	}

	public static int indexOfAny(String str, String searchStrs[]) {
		if (str == null || searchStrs == null)
			return -1;
		int sz = searchStrs.length;
		int ret = 2147483647;
		int tmp = 0;
		for (int i = 0; i < sz; i++) {
			String search = searchStrs[i];
			if (search != null) {
				tmp = str.indexOf(search);
				if (tmp != -1 && tmp < ret)
					ret = tmp;
			}
		}

		return ret != 2147483647 ? ret : -1;
	}

	public static int lastIndexOfAny(String str, String searchStrs[]) {
		if (str == null || searchStrs == null)
			return -1;
		int sz = searchStrs.length;
		int ret = -1;
		int tmp = 0;
		for (int i = 0; i < sz; i++) {
			String search = searchStrs[i];
			if (search != null) {
				tmp = str.lastIndexOf(search);
				if (tmp > ret)
					ret = tmp;
			}
		}

		return ret;
	}

	public static String substring(String str, int start) {
		if (str == null)
			return null;
		if (start < 0)
			start = str.length() + start;
		if (start < 0)
			start = 0;
		if (start > str.length())
			return "";
		else
			return str.substring(start);
	}

	public static String substring(String str, int start, int end) {
		if (str == null)
			return null;
		if (end < 0)
			end = str.length() + end;
		if (start < 0)
			start = str.length() + start;
		if (end > str.length())
			end = str.length();
		if (start > end)
			return "";
		if (start < 0)
			start = 0;
		if (end < 0)
			end = 0;
		return str.substring(start, end);
	}

	public static String left(String str, int len) {
		if (str == null)
			return null;
		if (len < 0)
			return "";
		if (str.length() <= len)
			return str;
		else
			return str.substring(0, len);
	}

	public static String right(String str, int len) {
		if (str == null)
			return null;
		if (len < 0)
			return "";
		if (str.length() <= len)
			return str;
		else
			return str.substring(str.length() - len);
	}

	public static String mid(String str, int pos, int len) {
		if (str == null)
			return null;
		if (len < 0 || pos > str.length())
			return "";
		if (pos < 0)
			pos = 0;
		if (str.length() <= pos + len)
			return str.substring(pos);
		else
			return str.substring(pos, pos + len);
	}

	public static String substringBefore(String str, String separator) {
		if (str == null || separator == null || str.length() == 0)
			return str;
		if (separator.length() == 0)
			return "";
		int pos = str.indexOf(separator);
		if (pos == -1)
			return str;
		else
			return str.substring(0, pos);
	}

	public static String substringAfter(String str, String separator) {
		if (str == null || str.length() == 0)
			return str;
		if (separator == null)
			return "";
		int pos = str.indexOf(separator);
		if (pos == -1)
			return "";
		else
			return str.substring(pos + separator.length());
	}

	public static String substringBeforeLast(String str, String separator) {
		if (str == null || separator == null || str.length() == 0
				|| separator.length() == 0)
			return str;
		int pos = str.lastIndexOf(separator);
		if (pos == -1)
			return str;
		else
			return str.substring(0, pos);
	}

	public static String substringAfterLast(String str, String separator) {
		if (str == null || str.length() == 0)
			return str;
		if (separator == null || separator.length() == 0)
			return "";
		int pos = str.lastIndexOf(separator);
		if (pos == -1 || pos == str.length() - separator.length())
			return "";
		else
			return str.substring(pos + separator.length());
	}

	public static String substringBetween(String str, String tag) {
		return substringBetween(str, tag, tag);
	}

	public static String substringBetween(String str, String open, String close) {
		if (str == null || open == null || close == null)
			return null;
		int start = str.indexOf(open);
		if (start != -1) {
			int end = str.indexOf(close, start + open.length());
			if (end != -1)
				return str.substring(start + open.length(), end);
		}
		return null;
	}

	public static String[] getSubStringBetween(String str, String open,
			String close) {
		if (str == null || open == null || close == null)
			return new String[0];
		int length = str.length();
		if (length == 0)
			return new String[0];
		List<String> lstTemp = new ArrayList<String>();
		int beg = 0;
		for (int end = 0; end < length;) {
			beg = str.indexOf(open);
			if (beg != -1) {
				end = str.indexOf(close, beg + open.length());
				if (end != -1) {
					lstTemp.add(str.substring(beg + open.length(), end));
					str = str.substring(end + 1, length);
					length = str.length();
					end = 0;
				} else {
					end = length;
				}
			} else {
				end = length;
			}
		}

		return (String[]) lstTemp.toArray(new String[lstTemp.size()]);
	}

	public static String upperCase(String str) {
		if (str == null)
			return null;
		else
			return str.toUpperCase();
	}

	public static String lowerCase(String str) {
		if (str == null)
			return null;
		else
			return str.toLowerCase();
	}

	public static boolean isNumeric(String str) {
		if (str == null)
			return false;
		int sz = str.length();
		for (int i = 0; i < sz; i++)
			if (!Character.isDigit(str.charAt(i)))
				return false;

		return true;
	}

	public static boolean isNumericSpace(String str) {
		if (str == null)
			return false;
		int sz = str.length();
		for (int i = 0; i < sz; i++)
			if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != ' ')
				return false;

		return true;
	}

	public static boolean isWhitespace(String str) {
		if (str == null)
			return false;
		int sz = str.length();
		for (int i = 0; i < sz; i++)
			if (!Character.isWhitespace(str.charAt(i)))
				return false;

		return true;
	}

	public static String reverse(String str) {
		if (str == null)
			return null;
		else
			return (new StringBuffer(str)).reverse().toString();
	}

	public static String toString(long lArray[]) {
		if (lArray == null)
			return "null";
		if (lArray.length == 0)
			return "[]";
		StringBuffer sb = new StringBuffer();
		sb.append('[');
		sb.append(lArray[0]);
		for (int i = 1; i < lArray.length; i++) {
			sb.append(", ");
			sb.append(lArray[i]);
		}

		sb.append("]");
		return sb.toString();
	}

	public static String toString(int iArray[]) {
		if (iArray == null)
			return "null";
		if (iArray.length == 0)
			return "[]";
		StringBuffer sb = new StringBuffer();
		sb.append('[');
		sb.append(iArray[0]);
		for (int i = 1; i < iArray.length; i++) {
			sb.append(", ");
			sb.append(iArray[i]);
		}

		sb.append("]");
		return sb.toString();
	}

	public static String toString(short sArray[]) {
		if (sArray == null)
			return "null";
		if (sArray.length == 0)
			return "[]";
		StringBuffer sb = new StringBuffer();
		sb.append('[');
		sb.append(sArray[0]);
		for (int i = 1; i < sArray.length; i++) {
			sb.append(", ");
			sb.append(sArray[i]);
		}

		sb.append("]");
		return sb.toString();
	}

	public static String toString(char cArray[]) {
		if (cArray == null)
			return "null";
		if (cArray.length == 0)
			return "[]";
		StringBuffer sb = new StringBuffer();
		sb.append('[');
		sb.append(cArray[0]);
		for (int i = 1; i < cArray.length; i++) {
			sb.append(", ");
			sb.append(cArray[i]);
		}

		sb.append("]");
		return sb.toString();
	}

	public static String toString(byte bArray[]) {
		if (bArray == null)
			return "null";
		if (bArray.length == 0)
			return "[]";
		StringBuffer sb = new StringBuffer();
		sb.append('[');
		sb.append(bArray[0]);
		for (int i = 1; i < bArray.length; i++) {
			sb.append(", ");
			sb.append(bArray[i]);
		}

		sb.append("]");
		return sb.toString();
	}

	public static String toString(boolean bArray[]) {
		if (bArray == null)
			return "null";
		if (bArray.length == 0)
			return "[]";
		StringBuffer sb = new StringBuffer();
		sb.append('[');
		sb.append(bArray[0]);
		for (int i = 1; i < bArray.length; i++) {
			sb.append(", ");
			sb.append(bArray[i]);
		}

		sb.append("]");
		return sb.toString();
	}

	public static String toString(float fArray[]) {
		if (fArray == null)
			return "null";
		if (fArray.length == 0)
			return "[]";
		StringBuffer sb = new StringBuffer();
		sb.append('[');
		sb.append(fArray[0]);
		for (int i = 1; i < fArray.length; i++) {
			sb.append(", ");
			sb.append(fArray[i]);
		}

		sb.append("]");
		return sb.toString();
	}

	public static String toString(double dArray[]) {
		if (dArray == null)
			return "null";
		if (dArray.length == 0)
			return "[]";
		StringBuffer sb = new StringBuffer();
		sb.append('[');
		sb.append(dArray[0]);
		for (int i = 1; i < dArray.length; i++) {
			sb.append(", ");
			sb.append(dArray[i]);
		}

		sb.append("]");
		return sb.toString();
	}

	public static String toString(Object objArray[]) {
		if (objArray == null)
			return "null";
		if (objArray.length == 0)
			return "[]";
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < objArray.length; i++) {
			if (i == 0)
				sb.append('[');
			else
				sb.append(", ");
			sb.append(String.valueOf(objArray[i]));
		}

		sb.append("]");
		return sb.toString();
	}

	public static String valueOf(Object o) {
		return o != null ? o.toString() : "";
	}

	public static String convertToStr(Object obj) {
		String str = "";
		if (!isEmpty(obj)) {
			str = obj.toString().trim();
		}
		return str;
	}

	public static String convertUnicodeToUtf8(Object obj) {
		try {
			return new String(convertToStr(obj).getBytes("ISO8859_1"), "utf-8");
		} catch (java.io.UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static boolean isEmpty(Object obj) {
		boolean result = true;
		try {
			if (obj == null) {
				return true;
			}
			Class<? extends Object> cls = obj.getClass();

			if (cls.isArray()) {
				Object[] objs = (Object[]) obj;
				if (objs.length > 0) {
					result = false;
				}
			}
			if (obj instanceof String && !obj.toString().trim().equals("")) {
				result = false;
			}
			if (obj instanceof Collection) {
				Collection<?> coll = (Collection<?>) obj;
				if (!coll.isEmpty()) {
					result = false;
				}
			}
			if (obj instanceof Map) {
				Map<?, ?> map = (Map<?, ?>) obj;
				if (!map.isEmpty()) {
					result = false;
				}
			}
			if (obj instanceof Number) {
				Number num = (Number) obj;
				if (!num.toString().trim().equals("")) {
					result = false;
				}
			}
			if (obj instanceof Date) {
				Date date = (Date) obj;
				if (null != date) {
					result = false;
				}
			}			
			if (obj instanceof Character) {
				Character character = (Character)obj;
				if (!character.toString().trim().equals("")) {
					result = false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String dateToString(Object obj, String format) {
		if (null == obj) {
			return "";
		}
		if (isEmpty(format)) {
			format = "yyyy-MM-dd HH:mm";
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(obj);
	}

	public static String replaceChars(String str, char searchChar,
			char replaceChar) {
		if (str == null)
			return null;
		else
			return str.replace(searchChar, replaceChar);
	}

	public static String chomp(String str, String separator) {
		if (str == null || str.length() == 0 || separator == null)
			return str;
		if (str.endsWith(separator))
			return str.substring(0, str.length() - separator.length());
		else
			return str;
	}

	/**
	 * 数据类型转换
	 * 
	 * @param obj
	 * @param cls
	 * @return
	 */
	public static Object converstToType(Object obj, Class<?> cls) {
		Object result = null;
		String temp = StringUtil.convertToStr(obj);
		if (cls == BigDecimal.class) {
			result = new BigDecimal(temp);
		} else if (cls == BigInteger.class) {
			result = new BigInteger(temp);
		} else if (cls == Date.class) {
			result = DateUtil.convertToDate(obj);
		} else if (cls == Double.class || cls == double.class) {
			result = Double.valueOf(temp);
		} else if (cls == Float.class || cls == float.class) {
			result = Float.valueOf(temp);
		} else if (cls == Long.class || cls == long.class) {
			if (StringUtil.isNotBlank(temp)) {
				result = Long.valueOf(temp);
			}
		} else if (cls == Integer.class || cls == int.class) {
			result = Integer.valueOf(temp);
		} else {
			result = temp;
		}
		return result;
	}
	
	/**
	 * 字符串补零，如果flag=true,则是右边补零，否则左边补零
	 * @param str
	 * @param strLength
	 * @param flag
	 * @return
	 */
	 public static String addZeroForNum(String str, int strLength, boolean flag) {
		    int strLen = str.length();
		    StringBuilder sb = new StringBuilder();
		     while (strLen < strLength) {
		           
		           if(flag)
		           {
		        	   sb.append(str).append("0");//右(后)补0
		           }
		           else
		           {
		        	   sb.append("0").append(str);// 左(前)补0
		           }
		           str = sb.toString();
		           strLen = str.length();
		     }
		    return str;
	}
	 
	 
	/**
	 * 格式化金额类型数据 
	 * @param str  金额数据
	 * @param len  加上小数点位数
	 * @return
	 */
	public static String formatAmt(String str, int len)
	{
		String result = "";
		if(isNotEmpty(str))
		{
			if(contains(str, AMOUNT_DOT))
			{
				String indexStr = str.substring(0, str.indexOf(AMOUNT_DOT));
				String tem = addZeroForNum(str.substring(str.indexOf(AMOUNT_DOT)), len, true);
				result = indexStr + tem;
			}
			else
			{
				String tem = addZeroForNum(AMOUNT_DOT, len, true);
				result = str + tem;
			}
		}
		return result;
	}
	
	// 过滤特殊字符  
    public static String stringFilter(String str, String regEx) throws PatternSyntaxException   
    {     
                // 只允许字母和数字       
                // String   regEx  =  "[^a-zA-Z0-9]";                     
                   // 清除掉所有特殊字符  
//          String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";  
          Pattern   p   =   Pattern.compile(regEx);     
          Matcher   m   =   p.matcher(str);     
          return   m.replaceAll("").trim();     
     }  
    
    private static boolean isMatch(String regex, String orginal){  
        if (orginal == null || orginal.trim().equals("")) {  
            return false;  
        }  
        Pattern pattern = Pattern.compile(regex);  
        Matcher isNum = pattern.matcher(orginal);  
        return isNum.matches();  
    }  
    
    public static boolean isPositiveInteger(String orginal) {  
        return isMatch("^\\+{0,1}[1-9]\\d*", orginal);  
    }  
    
    public static boolean isPositiveDecimal(String orginal){  
        return isMatch("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,6})?$", orginal);  
    }  
    
    
    /** 
     * 替换字符串中特殊字符 
     */  
    public static String encodeString(String strData)  
    {  
        if (strData == null)  
        {  
            return "";  
        }  
        strData = replaceString(strData, "&", "&amp;");  
        strData = replaceString(strData, "<", "&lt;");  
        strData = replaceString(strData, ">", "&gt;");  
        strData = replaceString(strData, "'", "&apos;");  
        strData = replaceString(strData, "\"", "&quot;");  
        return strData;  
    } 
    
    /** 
     * 替换一个字符串中的某些指定字符 
     * @param strData String 原始字符串 
     * @param regex String 要替换的字符串 
     * @param replacement String 替代字符串 
     * @return String 替换后的字符串 
     */  
    public static String replaceString(String strData, String regex,  
            String replacement)  
    {  
        if (strData == null)  
        {  
            return null;  
        }  
        int index;  
        index = strData.indexOf(regex);  
        StringBuilder sb = new StringBuilder("");
        if (index >= 0)  
        {  
            while (index >= 0)  
            {  
            	sb.append(strData.substring(0, index) + replacement);
                strData = strData.substring(index + regex.length());  
                index = strData.indexOf(regex);  
            }  
            sb.append(strData);
            return sb.toString();  
        }  
        return strData;  
    }
    
    
    /** 
     * 还原字符串中特殊字符 
     */  
    public static String decodeString(String strData)  
    {  
        strData = replaceString(strData, "&lt;", "<");  
        strData = replaceString(strData, "&gt;", ">");  
        strData = replaceString(strData, "&apos;", "'");  
        strData = replaceString(strData, "&quot;", "\"");  
        strData = replaceString(strData, "&amp;", "&");  
        return strData;  
    }
    
    /**
     * 
    * @MethodName: formatStringByIndicatePlaceholder
    * @Description: 字符串参数替换
    * @param: toBeReplacedStr  替换前的原字符串
    * @param: placeholder  占位符
    * @param: toBeReplacedStr  参数字符串数组
    * @return String    参数替换后的字符串
    * @throws
     */
	public static String formatStringByIndicatePlaceholder(String toBeReplacedStr, String placeholder, String[] params)
	{
		if(isNotEmpty(toBeReplacedStr)){
	    	StringBuilder sb = new StringBuilder(512);
	    	String[] strs = toBeReplacedStr.split(placeholder);
	 		for(int index = 0; index <= strs.length - 1; index++){
	 			sb.append(strs[index]);
	 			if(index <= params.length - 1)
	 				sb.append(params[index]);
			}
	 		return sb.toString();
		}else{
			return "";
		}
	}
	
	//替换所有数据库查询的特殊字符
	public static String replaceHtml(String str)
	{
		if(isBlank(str))
		{
			return str;
		}
		else
		{
			//替换掉所有的数据库查询出的特殊字符
			str = str.replaceAll("\r\n", ""); 
			str = str.replaceAll("\n\r", "<br>  ");
			str = str.replaceAll("\t", "    ");
			str = str.replaceAll("\"", "\\" + "\"");
		}
		return str;
	}
	
	
	public static String encodeDownloadFileName(String fileName) {
		String newFileName = fileName;
		try {
			return new String(newFileName.getBytes("gb2312"), "iso8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return newFileName;
	}
	public static String substringFileName(String allFileName){
		return allFileName.substring(0, allFileName.lastIndexOf('.'));
	}
	

}
